<template>
  <view class="container">
    <view class="tab-box">
      <u-tabs
          :list="tabsList"
          @change="tabsClick"
          :current="current"
          lineColor="#0962c4"
          :activeStyle="{
          color: '#333333',
          fontWeight: 'bold',
          fontSize: '36rpx'
        }"
          :inactiveStyle="{
          color: '#333333',
          fontWeight: 'normal',
          fontSize: '36rpx'
        }"
          bgColor="transparent"
      ></u-tabs>
    </view>
    <scroll-view scroll-y class="form-scroll">
      <view class="form-section">
        <view class="form-item">
          <view class="form-label required">名称</view>
          <input
              class="form-input"
              v-model="formData.name"
              placeholder="请输入名称"
              maxlength="100"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">编码</view>
          <input
              class="form-input"
              v-model="formData.code"
              placeholder="请输入编码"
              maxlength="50"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">分类</view>
          <view class="form-input picker" @click="dialogCategory = true">
            <text>{{ formData.category_name || '请选择分类' }}</text>
            <u-icon name="arrow-right" size="28" color="#999"></u-icon>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label required">规格型号</view>
          <input
              class="form-input"
              v-model="formData.specification"
              placeholder="请输入规格型号"
              maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">计量单位</view>
          <input
              class="form-input"
              v-model="formData.unit"
              placeholder="请输入计量单位"
              maxlength="20"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">数量</view>
          <input
              class="form-input"
              v-model="formData.quantity"
              type="digit"
              placeholder="请输入数量"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">技术状况</view>
          <picker
              class="form-input picker"
              style="width: 100%;display: flex;justify-content:space-between"
              :range="conditionOptions"
              range-key="label"
              @change="handleConditionChange"
          >
            <text>{{ formData.condition || '请选择技术状况' }}</text>
            <u-icon name="arrow-right" size="28" color="#999"></u-icon>
          </picker>
        </view>

        <view class="form-item">
          <view class="form-label required">所在省市</view>
          <view class="form-input picker" @click="dialogProvince = true">
            <text>{{ formData.province ? formData.province + formData.city : '请选择所在省市' }}</text>
            <u-icon name="arrow-right" size="28" color="#999"></u-icon>
          </view>
        </view>

        <view class="form-item">
          <view class="form-label required">详细地址</view>
          <input
              class="form-input"
              v-model="formData.address"
              placeholder="请输入详细地址"
              maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="form-label required">所属单位</view>
          <input
              class="form-input"
              v-model="formData.project_name"
              placeholder="请输入单位名称"
              maxlength="100"
          />
        </view>

        <view class="form-item">
          <view class="form-label">单位原值</view>
          <input
              class="form-input"
              v-model="formData.unit_price"
              type="digit"
              placeholder="请输入单位原值"
          />
        </view>

        <view class="form-item">
          <view class="form-label">折扣率(%)</view>
          <input
              class="form-input"
              v-model="formData.discount_rate"
              type="digit"
              placeholder="请输入折扣率"
          />
        </view>

        <view class="form-item">
          <view class="form-label">租售价格</view>
          <input
              class="form-input"
              v-model="formData.rental_price"
              placeholder="请输入租售价格"
          />
        </view>
        <view class="form-item">
          <view class="form-label">封面图</view>
          <view class="cover-upload-box">
            <view class="cover-preview" v-if="formData.post_url" @click="previewCover">
              <image class="cover-image" :src="formData.post_url" mode="aspectFill"></image>
              <view class="delete-icon" @click.stop="deleteCover">
                <u-icon name="close" color="#fff" size="24"></u-icon>
              </view>
            </view>
            <view class="cover-upload-add" @click="chooseCover" v-if="!formData.post_url">
              <u-icon name="plus" size="40" color="#ddd"></u-icon>
              <text class="upload-text">上传封面图</text>
            </view>
          </view>
          <view class="upload-tip">建议尺寸800x800像素以上，作为列表展示的主图</view>
        </view>

        <view class="form-item">
          <view class="form-label ">宣传图片</view>
          <view class="upload-box">
            <view
                class="upload-item"
                v-for="(item, index) in formData.images"
                :key="index"
                @click="previewImage(index)"
            >
              <image class="upload-image" :src="item" mode="aspectFill"></image>
              <view class="delete-icon" @click.stop="deleteImage(index)">
                <u-icon name="close" color="#fff" size="24"></u-icon>
              </view>
            </view>
            <view class="upload-add" @click="chooseImage" v-if="formData.images.length < 9">
              <u-icon name="plus" size="40" color="#ddd"></u-icon>
            </view>
          </view>
          <view class="upload-tip">最多上传9张图片，建议尺寸800x800像素以上</view>
        </view>

        <view class="form-item">
          <view class="form-label ">备注</view>
          <textarea
              class="form-textarea"
              v-model="formData.remark"
              placeholder="请详细备注的用途、状态、使用方法等信息"
              maxlength="500"
          ></textarea>
        </view>
      </view>

      <view class="form-section">
        <view class="form-item switch-item">
          <view class="switch-label">是否上架</view>
          <view class="switch-value">
            <text>{{ formData.is_public ? '上架' : '下架' }}</text>
            <switch
                :checked="formData.is_public"
                @change="togglePublic"
                color="#0962c4"
                style="transform:scale(0.8)"
            />
          </view>
        </view>
      </view>
    </scroll-view>

    <u-popup mode="bottom" v-model="dialogCategory" border-radius="24">
      <view class="popup-content" >
        <view class="popup-header">
          <text class="cancel-btn" @click="handleClose('dialogCategory')">重置</text>
          <text class="title">选择分类</text>
          <text class="confirm-btn" @click="handleConfirm('dialogCategory')">确定</text>
        </view>
        <view class="category-container">
          <scroll-view class="primary-category" scroll-y>
            <view
                v-for="(item, index) in primaryList"
                :key="index"
                :class="['primary-item', { active: searchParams.main_category_id === item.id }]"
                @click="handlePrimarySelect(item)"
            >
              <view class="active-bar" v-if="searchParams.main_category_id === item.id"></view>
              <text>{{ item.name }}</text>
            </view>
          </scroll-view>
          <scroll-view class="secondary-category" scroll-y>
            <view class="secondary-grid">
              <view
                  v-for="(item, index) in currentSecondaryList"
                  :key="index"
                  :class="['secondary-item', { selected: searchParams.category_id === item.id }]"
                  @click="handleSecondarySelect(item)"
              >
                <view class="icon-wrapper">
                  <image :src="item.icon" style="width: 80%;height: 80%"></image>
                </view>
                <text class="name">{{ item.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>
    <u-popup mode="bottom" v-model="dialogProvince" border-radius="24">
      <view class="popup-content" >
        <view class="popup-header">
          <text class="cancel-btn" @click="handleClose('dialogProvince')">重置</text>
          <text class="title">选择地区</text>
          <text class="confirm-btn" @click="handleConfirm('dialogProvince')">确定</text>
        </view>
        <view class="category-container">
          <scroll-view class="primary-category" scroll-y>
            <view
                v-for="(item, index) in primaryList2"
                :key="index"
                :class="['primary-item', { active: searchParams.province === item.name }]"
                @click="handlePrimarySelect2(item)"
            >
              <view class="active-bar" v-if="searchParams.province === item.name"></view>
              <text>{{ item.name }}</text>
            </view>
          </scroll-view>
          <scroll-view class="secondary-category" scroll-y>
            <view class="secondary-grid city">
              <view
                  v-for="(item, index) in currentSecondaryList2"
                  :key="index"
                  :class="['secondary-item city', { selected: searchParams.city === item.name }]"
                  @click="handleSecondarySelect2(item)"
              >
                <text class="name">{{ item.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-popup>
    <view class="submit-box">
      <button class="submit-btn" @click="submitForm">发布</button>
    </view>
  </view>
</template>

<script>
import Navbar from "../../components/navbar.vue";
import { mapGetters } from 'vuex'
import { cityList } from '@/config/city.js'
export default {
  name: "ResourcePublish",
  components: {
    Navbar
  },

  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      tabsList: [
        { name: '设备', value: '设备' },
        { name: '物资', value: '物资' }
      ],
      current: 0,
      formData: {
        post_url: '',
        images: [],
        code: '',
        name: '',
        type: '物资',
        category_id: '',
        category_name: '',
        specification: '',
        unit: '',
        quantity: 1,
        condition: '良好', // 默认全新
        condition_text: '良好',
        status: 'available',
        province: '',
        city: '',
        address: '',
        project_id: 0,
        project_name: '',
        unit_price: 0,
        total_price: 0,
        discount_rate: 100,
        rental_price: '',
        contact_name: '',
        contact_phone: '',
        remark: '',
        is_public: 1,
        create_user_id: 0,
        create_user_name: ''
      },
      searchParams: {
        main_category_id: '',
        category_id: '',
        category_name: '',
        createTimeSort: '',
        province: '',
        city: ''
      },
      conditionOptions: [
        { value: '良好', label: '良好' },
        { value: '一般', label: '一般' },
      ],
      dialogCategory: false,
      dialogProvince: false,
      primaryList: [],
      currentSecondaryList: [],
      primaryList2: cityList,
      currentSecondaryList2: [],
      showCategoryPicker: false,
      showDepartmentPicker: false,
    };
  },
  onShow() {
    if (!this.userInfo.id) {
      uni.showToast({
        icon: 'none',
        title: '请先登录'
      })
      uni.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        confirmText: '确定',
        success: function (res) {
          if (res.confirm) {
            uni.switchTab({
              url: '/pages/my/index'
            })
          }
        }
      })
      return
    } else {
      console.log(this.userInfo,'userinfo')
      if (this.userInfo.level != 1 && this.userInfo.level != 2) {
        uni.showModal({
          title: '提示',
          content: '非管理员，不能发布',
          showCancel: false,
          confirmText: '确定',
          success: function (res) {
            if (res.confirm) {
              uni.switchTab({
                url: '/pages/resource/index'
              })
            }
          }
        })
        return
      }
        this.formData.create_user_id = this.userInfo.id || '';
        this.formData.create_user_name = this.userInfo.nickname || '';
      this.getCategoryList()
    }
  },
  methods: {
    getCategoryList() {
      uni.showLoading()
      this.$api.getCategoryTree({
        type: this.tabsList[this.current].value
      }).then(res => {
        this.primaryList = res || []
        if (this.primaryList.length) {
          this.searchParams.main_category_id = res[0].id
          this.currentSecondaryList = res[0].children || []
        }
        this.searchParams.category_id = ''
        this.searchParams.main_category_id = ''
        this.searchParams.category_name = ''
      }).catch(err => {
        console.error('获取分类失败', err)
        uni.showToast({
          title: '获取分类失败',
          icon: 'none'
        })
      }).finally(() => {
        uni.hideLoading()
      })
    },
    tabsClick(index) {
      this.current = index;
      this.formData.type = this.tabsList[index].value;
      this.getCategoryList()
    },
    handlePrimarySelect(item) {
      this.searchParams.main_category_id = item.id
      this.searchParams.category_id = item.id
      this.searchParams.category_name = item.name
      this.currentSecondaryList = item.children || []
    },
    handleSecondarySelect(item) {
      this.searchParams.category_id = item.id;
      this.searchParams.category_name = item.name;
    },
    handlePrimarySelect2(item) {
      this.searchParams.province = item.name
      this.currentSecondaryList2 = item.children
    },
    handleSecondarySelect2(item) {
      this.searchParams.city = item.name
    },
    handleClose(key) {
      if (key === 'dialogCategory') {
        this.searchParams.main_category_id = ''
        this.searchParams.category_id = ''
        this.searchParams.category_name = ''
        this.currentSecondaryList = []
      } else {
        this.searchParams.province = ''
        this.searchParams.city = ''
        this.currentSecondaryList2 = []
      }
    },
    handleConfirm(key) {
      if (key === 'dialogCategory') {
        this.formData.category_id =this.searchParams.category_id || this.searchParams.main_category_id || 0;
        this.formData.category_name = this.searchParams.category_name;
      } else if (key === 'dialogProvince') {
        if (this.searchParams.province) {
          this.formData.province = this.searchParams.province;
          this.formData.city = this.searchParams.city;
        } else {
          this.formData.province = '';
          this.formData.city = '';
          uni.showToast({
            title: '请选择省市',
            icon: 'none'
          })
        }
      }
      this[key] = false;
    },
    handleConditionChange(e) {
      const index = e.detail.value;
      this.formData.condition = this.conditionOptions[index].value;
    },
    // 选择图片
    chooseImage() {
      let that = this
      uni.chooseImage({
        count: 9 - this.formData.images.length,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          console.log(res)
          res.tempFilePaths.forEach((item,index) => {
            that.uploadImages(item, index);
          })
        }
      });
    },
    // 上传图片
    uploadImages(file) {
      console.log(file)
      let that = this
      uni.uploadFile({
        url: that.$baseUrl + '/upload/file', // 仅为示例,非真实的接口地址
        filePath: file,
        name: 'file',
        success: (uploadFileRes) => {
          let res = JSON.parse(uploadFileRes.data)
          // 上传完成需要更新 formData.images
          that.formData.images.push(res.data.url);
        }
      });

    },
    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: this.formData.images[index],
        urls: this.formData.images
      });
    },
    // 删除图片
    deleteImage(index) {
      this.formData.images.splice(index, 1);
    },
    // 切换是否公开
    togglePublic(e) {
      this.formData.is_public = e.detail.value ? 1 : 0;
    },
    // 切换是否允许转让
    toggleTransfer(e) {
      this.formData.allow_transfer = e.detail.value ? 1 : 0;
    },
    // 提交表单
    async submitForm() {
      if (!this.userInfo.id) {
        this.showToast('请先登录');
        return;
      }
      // 表单验证
      if (!this.formData.name) {
        this.showToast('请输入名称');
        return;
      }

      if (!this.formData.category_name) {
        this.showToast('请选择分类');
        return;
      }

      if (!this.formData.specification) {
        this.showToast('请输入规格型号');
        return;
      }

      if (!this.formData.unit) {
        this.showToast('请输入计量单位');
        return;
      }

      if (!this.formData.quantity || this.formData.quantity <= 0) {
        this.showToast('请输入有效数量');
        return;
      }

      if (!this.formData.province) {
        this.showToast('请选择所在省市');
        return;
      }

      if (!this.formData.address) {
        this.showToast('请输入详细地址');
        return;
      }

      if (!this.formData.project_name) {
        this.showToast('请输入所属单位');
        return;
      }

      // 处理图片字符串
      const imagesStr = this.formData.images.join(',');
      const submitData = {
        ...this.formData,
        images: imagesStr
      };

      // 提交表单
      uni.showLoading({
        title: '提交中...'
      });

      // 模拟API调用
      console.log('提交数据:', submitData);
      if (this.formData.id) {
        await this.$api.updateIdleItem(submitData)
      } else {
        await this.$api.createIdleItem(submitData)
      }
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      });
      // 模拟成功响应
      setTimeout(() => {
        uni.hideLoading();
        uni.navigateBack()
        // 返回列表页
      }, 1000);
    },
    // 显示提示
    showToast(title) {
      uni.showToast({
        title: title,
        icon: 'none'
      });
    },
    // 选择封面图
    chooseCover() {
      let that = this
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          uni.uploadFile({
            url: that.$baseUrl + '/upload/file', // 仅为示例,非真实的接口地址
            filePath: res.tempFilePaths[0],
            name: 'file',
            success: (uploadFileRes) => {
              let res = JSON.parse(uploadFileRes.data)
              // 上传完成需要更新 formData.images
              that.formData.post_url = res.data.url;
            }
          });
        }
      });
    },
    // 上传封面图
    uploadCover(tempFilePath) {
      // 模拟上传封面图
      this.formData.post_url = tempFilePath;
    },
    // 预览封面图
    previewCover() {
      uni.previewImage({
        urls: [this.formData.post_url]
      });
    },
    // 删除封面图
    deleteCover() {
      this.formData.post_url = '';
    },
  }
};
</script>

<style lang="scss">
.popup-content {
  background-color: #ffffff;
  position: relative;
  padding-top: 0 !important;
}

.popup-header {
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  border-bottom: 1px solid #f5f5f5;
}

.cancel-btn {
  font-size: 14px;
  color: #666666;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.confirm-btn {
  font-size: 14px;
  color: #0962c4;
}

.category-container {
  display: flex;
  height: calc(100% - 136rpx);
}

.primary-category {
  width: 30%;
  background-color: #f8f8f8;
  overflow: auto;
}

.primary-item {
  height: 96rpx;
  display: flex;
  align-items: center;
  padding-left: 32rpx;
  position: relative;
}

.primary-item.active {
  background-color: #ffffff;
}

.active-bar {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 32rpx;
  background-color: #0962c4;
  border-radius: 3rpx;
}

.secondary-category {
  flex: 1;
  overflow: auto;
}

.secondary-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 32rpx;
}
.secondary-grid.city {
  display: block;
  flex-wrap: nowrap;
  padding: 32rpx;
}
.secondary-item {
  width: calc(33.33% - 32rpx);
  margin: 0 16rpx 32rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.secondary-item.city {
  width: 100%;
  height: 96rpx;
  flex-direction: row;
  padding: 0 32rpx;
  margin: 0;
  margin-bottom: 16rpx;
  border-radius: 18rpx;
}

.icon-wrapper {
  width: 112rpx;
  height: 112rpx;
  border-radius: 16rpx;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16rpx;
}

.secondary-item.selected .icon-wrapper {
  background-color: #e3f2fd;
  border: 2rpx solid #0962c4;
}
.secondary-item.selected .name {
  color: #0962c4;
}
.secondary-item.city.selected {
  background-color: #e3f2fd;
}
.name {
  font-size: 14px;
  color: #333333;
  width: 100%;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.popup-content {
  padding: 24rpx;
}
.category-container {
  display: flex;
  height: 600rpx;
  border-bottom: 1px solid #DCDCDC;
}
.confirm-btn {
  font-size: 28rpx;
  color: #0962c4;
}
page {
  height: 100%;
  overflow: auto;
}
.container {
  display: flex;
  flex-direction: column;
  padding-bottom: 200rpx;
}

.form-scroll {
  flex: 1;
  overflow: hidden;
}

.form-section {
  background-color: #fff;
  padding: 0 30rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    padding: 30rpx 0 20rpx;
  }
}

.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;

    &.required::before {
      content: '*';
      color: #FF3B30;
      margin-right: 6rpx;
    }
  }

  .form-input {
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;

    &.picker {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }

  .form-textarea {
    height: 240rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    width: 100%;
  }

  .textarea-counter {
    text-align: right;
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }

  &.switch-item {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .switch-label {
      font-size: 28rpx;
      color: #333;
    }

    .switch-value {
      display: flex;
      align-items: center;

      text {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
      }
    }
  }
}

.upload-box {
  display: flex;
  flex-wrap: wrap;

  .upload-item, .upload-add {
    width: 160rpx;
    height: 160rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    overflow: hidden;
  }

  .upload-item {
    position: relative;

    .upload-image {
      width: 100%;
      height: 100%;
    }

    .delete-icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 40rpx;
      height: 40rpx;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .upload-add {
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1rpx dashed #ddd;
  }
}

.cover-image {
  position: relative;
}
.delete-icon {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}
.cover-upload-box {
  display: flex;
  margin-top: 20rpx;
}

.cover-preview {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.cover-image {
  width: 100%;
  height: 100%;
}

.cover-upload-add {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.rule-list {
  .rule-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .rule-input {
      flex: 1;
      height: 80rpx;
      background-color: #f5f5f5;
      border-radius: 8rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }

    .delete-rule {
      padding: 0 20rpx;
    }
  }

  .add-rule {
    display: flex;
    align-items: center;
    color: #0962c4;
    font-size: 28rpx;
    padding: 20rpx 0;

    text {
      margin-left: 10rpx;
    }
  }
}

.form-tips {
  padding: 30rpx;
  text-align: center;

  text {
    font-size: 24rpx;
    color: #999;
  }
}

.submit-box {
  position: fixed;
  z-index: 9;
  left: 0;
  width: 100%;
  bottom: 50rpx;
  padding: 0 30rpx;

  .submit-btn {
    height: 90rpx;
    line-height: 90rpx;
    background-color: #0962c4;
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
  }
}
</style>
